<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;

class Box extends Frontend {

//补货
    public function index() {
//        $box_info = db('user_box')->where(['user_id' => $this->iUserId])->find();
//        if ($box_info) {
//            if ($box_info['status'] != 1) {
//                $this->redirect(url('applySuc'));
//            }
//        } else {
//            $this->redirect(url('nobox'));
//        }
//        $user_box_info = db('user_box')
//                ->where(['user_box_id' => $this->userBoxId, 'status' => 1])
//                ->find();
//
//        $goods_list = db('house_goods')
//                ->alias('hg')
//                ->field('g.goods_id,gb.brand_title,g.goods_title,g.goods_desc,g.goods_logo,g.goods_model,g.goods_spec,hg.selling_price')
//                ->join('fa_goods g', 'hg.goods_id=g.goods_id')
//                ->join('fa_goods_brand gb', 'g.brand_id = gb.brand_id')
//                ->where(['hg.house_id' => $user_box_info['quarters_id'], 'hg.is_del' => 0])
//                ->select();
////查询自己盒子的库存
//        foreach ($goods_list as &$val) {
//            $stock_num = db('user_box_goods')->where(['user_box_id' => $this->userBoxId, 'goods_id' => $val['goods_id']])->value('stock_num');
//            $val['stock_num'] = $stock_num ? $stock_num : 0;
//            $buy_num = db('cart')->where(['type' => 1, 'goods_id' => $val['goods_id']])->value('buy_num');
//            $val['buy_num'] = $buy_num ? $buy_num : 0;
//        }
//        unset($val);
        //TODO 获取当前小区内的商品

        $user_box_info = db('user_box')
                ->where(['user_box_id' => $this->userBoxId, 'status' => 1])
                ->find();

        $goods_ids = db('house_goods')
                ->alias('hg')
                ->where(['hg.house_id' => $user_box_info['quarters_id'], 'hg.is_del' => 0])
                ->column('goods_id');


//        $goods_ids = db('user_box_goods')->where(['user_box_id' => $this->userBoxId, 'is_del' => 0])->column('goods_id');

        $cate_ids = db('goods')->where('goods_id', 'in', $goods_ids)->column('cate_id');

        //TODO 获取当前小区内商品的类型
        $cate_list = db('goods_cate')->field('cate_id,cate_title')->where(['status' => 1, 'is_deleted' => 0, 'cate_id' => ['in', $cate_ids]])->order('sort desc')->select();

        $gwhere['g.is_deleted'] = 0;
        $gwhere['g.status'] = 1;
//        $gwhere['ubg.stock_num'] = ['gt', 0];
//        $gwhere['ubg.is_del'] = 0;
//        $gwhere['ubg.user_box_id'] = $this->userBoxId;
        $gwhere['hg.house_id'] = $user_box_info['quarters_id'];

        $i = 0;
        foreach ($cate_list as &$row) {
            $gwhere['g.cate_id'] = $row['cate_id'];
            $row['index_num'] = $i;
            $goods_list = db('house_goods')
                    ->alias('hg')
                    ->field('g.goods_id,gb.brand_title,g.goods_title,g.goods_desc,g.goods_logo,g.goods_model,g.goods_spec,hg.selling_price')
                    ->join('fa_goods g', 'hg.goods_id=g.goods_id')
                    ->join('fa_goods_brand gb', 'g.brand_id = gb.brand_id')
                    ->where($gwhere)
                    ->order('g.sort')
                    ->select();
            if ($goods_list) {
                //获取用户购物车数量
                foreach ($goods_list as &$val) {
                    $buy_num = db('cart')->where(['type' => 1, 'goods_id' => $val['goods_id'], 'user_box_id' => $this->userBoxId])->value('buy_num');
                    $val['buy_num'] = $buy_num ? $buy_num : 0;
                }
                $row['goods_list'] = $goods_list;
            } else {
                $row['goods_list'] = [];
            }
            $i++;
        }
        unset($row);


        $user_box_info['room_name'] = db('house')->where(['house_id' => $user_box_info['room_id']])->value('house_name');
        $user_box_info['unit_name'] = db('house')->where(['house_id' => $user_box_info['unit_id']])->value('house_name');
        $user_box_info['quarters_name'] = db('house')->where(['house_id' => $user_box_info['quarters_id']])->value('house_name');



        $this->assign('last_cate', $i - 1);
        $this->assign('cate_list', $cate_list);




        $box_no = db('box')->where(['box_id' => $user_box_info['box_id']])->value('box_no');
        $buhuo_config = db('configure')->where(['key' => 'buhuo'])->value('desc');
        $buhuo_config = json_decode($buhuo_config, true);
//返回购物车总商品数
        $cart = $this->getCartTotalByUserId($this->iUserId, $this->userBoxId);

        $this->assign('info', $user_box_info);
        $this->assign('cart', $cart);
        $this->assign('goods_list', $goods_list);
        $this->assign('box_no', $box_no);
        $this->assign('buhuo_config', $buhuo_config);
        return $this->view->fetch();
    }

//无盒子提示
    public function nobox() {
        return $this->view->fetch();
    }

//申请盒子
    public function apply() {

        if ($this->request->isPost()) {
            $city = $this->request->request('city');
            $quarters_id = $this->request->request('xq-id', 0);
            $unit_id = $this->request->request('dy-id', 0);
            $room_id = $this->request->request('fj-id', 0);
            $contacts = $this->request->request('contacts');
            $sex = $this->request->request('sex', 1);
            $telephone = $this->request->request('telephone');
            $remark = $this->request->request('remark');

            $arr = explode(',', $city);
            $name = $arr[count($arr) - 1];

            $area_info = db('area')->where('name', $name)->find();

            $city_info = db('area')->where('id', $area_info['pid'])->find();
            $province_info = db('area')->where('id', $city_info['pid'])->find();

            $data['apply_no'] = 'SQ' . time() . mt_rand(1000, 9999);
            $data['province'] = $province_info['id'];
            $data['province_name'] = $province_info['name'];
            $data['city'] = $city_info['id'];
            $data['city_name'] = $city_info['name'];
            $data['area'] = $area_info['id'];
            $data['area_name'] = $area_info['name'];
            $data['quarters_id'] = $quarters_id;
            $data['unit_id'] = $unit_id;
            $data['room_id'] = $room_id;
            $data['contacts'] = $contacts;
            $data['sex'] = $sex;
            $data['telephone'] = $telephone;
            $data['remark'] = $remark;
            $data['user_id'] = $this->iUserId;

            $res = db('user_box')->insert($data);

            if ($res) {
                $this->redirect(url('applySuc'));
            }
        } else {

            $reapply = input('reapply', 0); //是否重新申请
            $box_info = db('user_box')->where(['user_id' => $this->iUserId])->order('user_box_id desc')->find();

            if ($reapply == 0) {
                if ($box_info) {
                    if ($box_info['status'] != 1 && $box_info['status'] != 20) {
                        $this->redirect(url('applySuc'));
                    }
                }
            }

            $tel = db('configure')->where(['key' => 'kefudianhua'])->value('desc');
            $this->assign('tel', $tel);
            return $this->view->fetch();
        }
    }

    public function isApply() {
        $room_id = input('room_id', 0);

        //判断是否拉黑

        $room_info = db('house')->where(['house_id' => $room_id])->find();

        if ($room_info['status'] == 1) {
            $this->error('该房间已经进入黑名单了', [], 80);
        }

        $box_info = db('user_box')->where(['status' => ['ELT', 1], 'room_id' => $room_id])->order('user_box_id desc')->find();

        if ($box_info) {
            $this->error('已经申请过了', [], 70);
        }


        $this->success();
    }

    public function applySuc() {
        $box_info = db('user_box')->where(['user_id' => $this->iUserId])->order('user_box_id desc')->find();

        $this->assign('box_info', $box_info);
        return $this->view->fetch();
    }

    public function change() {
        $goods_id = $this->request->param('goods_id', 0);
        $ope = $this->request->param('ope', 0); //操作 0-减 1-增
        if ($goods_id == 0) {
            $this->error('请选择商品');
        }

        $where['goods_id'] = $goods_id;
        $where['user_id'] = $this->iUserId;
        $where['user_box_id'] = $this->userBoxId;
        $where['type'] = 1;

        $cart_info = db('cart')->where($where)->find();

        Db::startTrans();
        try {

            $code = 1;  //编码  1 正常加减 800删除一条购物车记录   801 新增一条购物车记录 
//如果已经添加过
            if ($cart_info) {
                $cwhere['id'] = $cart_info['id'];

//如果只剩最后一个商品
                if ($cart_info['buy_num'] == 1 && $ope == 0) {
                    db('cart')->where($cwhere)->delete();
                    $code = 80;
                }

                if ($ope == 1) {
                    $cdata['buy_num'] = $cart_info['buy_num'] + 1;
                } else {
                    $cdata['buy_num'] = $cart_info['buy_num'] - 1;
                }
                $cdata['updatetime'] = date('Y-m-d H:i:s', time());
                db('cart')->where($cwhere)->update($cdata);
            } else {

                $user_box_info = db('user_box')
                        ->where(['user_box_id' => $this->userBoxId, 'status' => 1])
                        ->find();

                $goods_info = db('house_goods')
                        ->alias('hg')
                        ->field('g.goods_id,g.goods_title,g.goods_desc,g.goods_logo,g.goods_spec,hg.selling_price')
                        ->join('fa_goods g', 'hg.goods_id=g.goods_id')
                        ->where(['hg.house_id' => $user_box_info['quarters_id'], 'hg.goods_id' => $goods_id, 'hg.is_del' => 0])
                        ->find();

//新增一条购物车
                $data['selling_price'] = isset($goods_info['selling_price']) ? $goods_info['selling_price'] : 0.00;
                $data['goods_id'] = $goods_id;
                $data['type'] = 1;
                $data['user_box_id'] = $this->userBoxId;
                $data['user_id'] = $this->iUserId;
                $data['updatetime'] = date('Y-m-d H:i:s', time());
                db('cart')->insert($data);
                $code = 81;
            }

//返回购物车总商品数
            $cart = $this->getCartTotalByUserId($this->iUserId, $this->userBoxId);
            Db::commit();
            $this->success('操作成功', $cart, $code);
        } catch (Exception $ex) {
            Db::rollback();
            $this->error('数据操作出错');
        }
    }

    public function comfirm() {
        $type = $this->request->param('type', 2); //类型 3-边吃边付 2-立即支付
        $remark = $this->request->param('remark');


//判断库存是否大于系统设置的值

        $user_box_info = db('user_box')
                ->where(['user_id' => $this->iUserId, 'status' => 1])
                ->find();

        $stock_num_sum = db('user_box_goods')
                ->field('sum(selling_price*stock_num) as sum_total')
                ->where(['user_box_id' => $this->userBoxId, 'is_del' => 0])
                ->find();

        $stock_num_sum = $stock_num_sum['sum_total'] ? $stock_num_sum['sum_total'] : 0;

        $buhuo_config = db('configure')->where(['key' => 'buhuo'])->value('desc');
        $buhuo_config = json_decode($buhuo_config, true);

        if ($buhuo_config['zongjian'] < $stock_num_sum) {
            $this->error('剩余商品大于￥' . $buhuo_config['zongjian'] . '元');
        }

//判断补货商品总金额是否满足

        $cart = $this->getCartTotalByUserId($this->iUserId, $this->userBoxId);

        if ($cart['total_price'] == 0) {
            $this->error('请选择要补货的商品');
        }

        if ($cart['total_price'] < $buhuo_config['jine']) {
            $this->error('商品金额低于￥' . $buhuo_config['jine']);
        }

        $total_price = $cart['total_price'];

        $data['desc'] = $remark;
        $data['user_box_id'] = $this->userBoxId;
        $data['user_id'] = $this->iUserId;
        $data['goods_price'] = $total_price;
        $data['type'] = $type;
        if ($type == 2) {
            if ($buhuo_config['zhekou'] == 0 || $buhuo_config['zhekou'] == 10) {
//不打折
            } else {
                $discount = $total_price * ($buhuo_config['zhekou'] / 10);
                $data['other_discount'] = $total_price - $discount;
                $total_price = $discount;

                if ($total_price < 0.01) {
                    $this->error('打完折后金额低于1分钱,无法支付');
                }
            }
        } else {
            $data['status'] = 1; //边吃边付不需要支付
        }

        $cart_goods = db('cart')
                ->field('goods_id,buy_num')
                ->where(['user_id' => $this->iUserId, 'user_box_id' => $this->userBoxId, 'type' => 1])
                ->select();
        if ($cart_goods) {
            //判断库存
            foreach ($cart_goods as &$val) {
                $goods_info = db('goods')
                        ->alias('g')
                        ->field('g.goods_id,g.goods_title,g.goods_model,g.goods_spec,g.goods_logo,gb.brand_title')
                        ->join('fa_goods_brand gb', 'g.brand_id = gb.brand_id')
                        ->where(['g.goods_id' => $val['goods_id'], 'g.status' => 1])
                        ->find();
                $val['goods_title'] = $goods_info['goods_title'];
                $val['goods_model'] = $goods_info['goods_model'];
                $val['goods_spec'] = $goods_info['goods_spec'];
                $val['goods_logo'] = $goods_info['goods_logo'];
                $val['brand_title'] = $goods_info['brand_title'];
            }
            unset($val);
        }
        Db::startTrans();
        try {

            $data['real_price'] = $total_price;

            $data['order_no'] = 'BH' . time() . mt_rand(1000, 9999);

            $order_id = db('order')->insertGetId($data);


            foreach ($cart_goods as &$row) {
                $row['order_id'] = $order_id;
                db('order_goods')->insert($row);
            }

            //删除购物车
            db('cart')->where(['user_id' => $this->iUserId, 'user_box_id' => $this->userBoxId, 'type' => 1])->delete();

            Db::commit();
            if ($type == 2) {
                $url = url('Order/selPay', array('out_trade_no' => $data['order_no'], 'type' => 2));
            } else {
                $url = url('suc');
            }
            $this->success('下单成功', ['url' => $url]);
        } catch (Exception $ex) {
            Db::rollback();
            $this->error('下单失败');
        }
    }

    public function suc() {
        return $this->view->fetch();
    }

    /**
     * 获取购物车总商品数和总价格
     * @param int $user_id 用户ID
     * @return array
     */
    function getCartTotalByUserId($user_id, $user_box_id = 0) {
//购物车数量及价格
        $cart['num'] = db('cart')
                ->where(['user_id' => $user_id, 'user_box_id' => $user_box_id, 'type' => 1])
                ->sum('buy_num');

        $total_price = db('cart')
                ->fieldRaw('SUM(buy_num*selling_price) as total_price')
                ->where(['user_id' => $user_id, 'user_box_id' => $user_box_id, 'type' => 1])
                ->find();

        $cart['total_price'] = $total_price['total_price'] ? $total_price['total_price'] : 0.00;

        return $cart;
    }

}
